package com.sohoometer.rsinterface;

//Java的串口开发
//MIMA集成
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.TooManyListenersException;

public class NetWorkToSeries {

	public static void main(String[] args) throws Exception {
		CommPortIdentifier identifier = CommPortIdentifier
				.getPortIdentifier("COM7");
		CommPort open1 = identifier.open("Hello", 2000);
		SerialPort open = (SerialPort) open1;
		// open.enableReceiveThreshold(18);
		open.disableReceiveThreshold();
		open.disableReceiveTimeout();
		// open.enableReceiveThreshold(48);
		// open.enableReceiveTimeout(5000);
		// open.disableReceiveFraming();
		open.setInputBufferSize(1024);
		// open.disableReceiveTimeout();
		open.setSerialPortParams(9600, SerialPort.DATABITS_8,
				SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
		int port = 7001;
		ServerSocket serverSocket = new ServerSocket(port);
		try {
			Thread rThread = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Socket socket = serverSocket.accept();
						OutputStream outputStream = open.getOutputStream();
						InputStream inputStream = open.getInputStream();
						InputStream netStreamInputStream = socket
								.getInputStream();
						OutputStream netStreamoutputStream = socket
								.getOutputStream();
						try {
							open.addEventListener(new MySeriesHandler(
									inputStream, netStreamoutputStream));
							open.notifyOnDataAvailable(true);
							Thread thread = new Thread(new Runnable() {
								@Override
								public void run() {
									while (true) {
										try {
											byte[] b = new byte[1024];
											int len = -1;
											ByteBuffer buffer = ByteBuffer.allocate(50);
											while ((len = netStreamInputStream
													.read(b)) > 0) {
												outputStream.write(b, 0, len);
												buffer.put(b,0,len);
												byte[] array = buffer.array();
												// 将所有的输入输出写到输出流中
												System.out.println("[网口收到数据:]"+Arrays.toString(array));
											}
											outputStream.flush();
										} catch (IOException e) {
											// TODO Auto-generated catch
											// block
											e.printStackTrace();
										}
									}
								}
							});
							thread.start();
						} catch (TooManyListenersException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} catch (IOException e) {
					}
				}
			});
			rThread.start();
			// InputStream inputStream = open.getInputStream();
			// //自定义流读取方式
			// open.addEventListener(new
			// MySeriesHandler(inputStream,outputStream));
			// open.notifyOnDataAvailable(true);
			// 主线程方式
			// Scanner scanner = new Scanner(System.in);
			// String s = "";
			// while (!(s = scanner.nextLine()).equals("bye")) {
			// outputStream.write(s.getBytes());
			// outputStream.flush();
			// }

			// 事件监听方式的读取

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	static void listPorts() {
		java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier
				.getPortIdentifiers();
		while (portEnum.hasMoreElements()) {
			CommPortIdentifier portIdentifier = portEnum.nextElement();
			System.out.println(portIdentifier.getName() + " - "
					+ getPortTypeName(portIdentifier.getPortType()));
		}
	}

	static String getPortTypeName(int portType) {
		switch (portType) {
		case CommPortIdentifier.PORT_I2C:
			return "I2C";
		case CommPortIdentifier.PORT_PARALLEL:
			return "Parallel";
		case CommPortIdentifier.PORT_RAW:
			return "Raw";
		case CommPortIdentifier.PORT_RS485:
			return "RS485";
		case CommPortIdentifier.PORT_SERIAL:
			return "Serial";
		default:
			return "unknown type";
		}
	}
}

class MySeriesHandler implements SerialPortEventListener {
	InputStream inputStream = null;
	OutputStream outputStream = null;

	public MySeriesHandler(InputStream inputStream, OutputStream outputStream) {
		this.inputStream = inputStream;
		this.outputStream = outputStream;
	}

	@Override
	public void serialEvent(SerialPortEvent event) {
		// try {
		// Thread.sleep(1000);
		// } catch (InterruptedException e1) {
		// // TODO Auto-generated catch block
		// e1.printStackTrace();
		// }
		switch (event.getEventType()) {
		case SerialPortEvent.BI: // 10
		case SerialPortEvent.OE: // 7
		case SerialPortEvent.FE: // 9
		case SerialPortEvent.PE: // 8
		case SerialPortEvent.CD: // 6
		case SerialPortEvent.CTS: // 3
		case SerialPortEvent.DSR: // 4
		case SerialPortEvent.RI: // 5
		case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2
			break;
		case SerialPortEvent.DATA_AVAILABLE: // 1
			byte[] b = new byte[1024];
			int i = 1;
			int len = -1;
			try {
				while (true) {
					ByteBuffer  byteBuffer = ByteBuffer.allocate(40);
					while ((len = inputStream.read(b)) > 0) {
						outputStream.write(b, 0, len); // 将所有的输入输出写到输出流中
						byteBuffer.put(b,0,len);
					}	
					if(byteBuffer.remaining()>2) {
						byte[] array = byteBuffer.array();
					System.out.println("[串口收到数据:]"+Arrays.toString(array));
					}
					outputStream.flush();
				}
				// len = inputStream.read(b);
				// System.out.println(new String(b));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}